package com.cet.algorithm.回溯.复原IP地址;

import java.util.LinkedList;
import java.util.List;

/**
 * @program: cet-practice
 * @description: 复原IP地址
 * @author: 陈恩涛
 * @create: 2023-05-30 17:50
 **/
public class LC93 {

    // 返回的合法IP地址集合
    List<String> result = new LinkedList<>();

    // ip地址
    StringBuilder path = new StringBuilder();

    // 分割符
    final String SEPARATOR = ".";

    // 分隔符可使用次数
    int SEPARATOR_TIMES = 4;

    public List<String> restoreIpAddresses(String s) {
        backTracing(s, 0);
        return result;
    }

    public void backTracing(String s, int startIdx) {

        // 已经来不及了
        if (3 * (SEPARATOR_TIMES) < s.length() - (path.length() - (4 - SEPARATOR_TIMES))) {
            return;
        }

        // 递归终止条件
        if (SEPARATOR_TIMES <= 0) {
            path.deleteCharAt(0);
            result.add(path.toString());
            path = new StringBuilder(SEPARATOR).append(path);
            return;
        }

        //单层递归逻辑
        for (int i = startIdx; i < s.length(); i++) {

            String subIp = s.substring(startIdx, i + 1);
            if (!isValid(subIp)) {
                break;
            }

            path.append(SEPARATOR).append(subIp);
            SEPARATOR_TIMES--;
            backTracing(s, i + 1);
            SEPARATOR_TIMES++;
            path.delete(path.lastIndexOf(SEPARATOR), path.length());
        }
    }

    // 判断ip字串是否合法
    public boolean isValid(String ip) {

        // 以0开头的整数非法
        if (ip.charAt(0) == '0' && ip.length() != 1) {
            return false;
        }

        int num = 0;

        for (int i = 0; i < ip.length(); i++) {
            if (ip.charAt(i) < '0' || ip.charAt(i) > '9') {
                return false;
            }
            num = num * 10 + ip.charAt(i) - '0';
            if (num > 255) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        LC93 lc93 = new LC93();
        System.out.println(lc93.restoreIpAddresses("0000"));
    }
}
